package files

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/files"
	"github.com/flipped-aurora/gin-vue-admin/server/service"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/flipped-aurora/gin-vue-admin/server/utils/upload"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"mime/multipart"
	"strconv"
)

type FilesApi struct{}

// UploadFile
// @Tags      ExaFileUploadAndDownload
// @Summary   上传文件示例
// @Security  ApiKeyAuth
// @accept    multipart/form-data
// @Produce   application/json
// @Param     file  formData  file                                                           true  "上传文件示例"
// @Success   200   {object}  response.Response{data=exampleRes.ExaFileResponse,msg=string}  "上传文件示例,返回包括文件详情"
// @Router    /fileUploadAndDownload/upload [post]
func (f *FilesApi) AddUploadFileInfo(c *gin.Context) {
	//获取上传文件的用户Id
	userId := utils.GetUserID(c)
	noSave := c.DefaultQuery("noSave", "0")
	_, header, err := c.Request.FormFile("file")
	if err != nil {
		global.GVA_LOG.Error("接收文件失败!", zap.Error(err))
		response.FailWithMessage("接收文件失败", c)
		return
	}
	typeStr, err := strconv.Atoi(c.Request.FormValue("type"))
	if err != nil {
		response.FailWithMessage("type类型错误", c)
		return
	}
	typeInfo := int8(typeStr)
	if err != nil {
		global.GVA_LOG.Error("接收文件类型失败!", zap.Error(err))
		response.FailWithMessage("接收文件类型失败", c)
		return
	}
	fileInfo, err := f.UploadFile(header, noSave, typeInfo, userId) // 文件上传后拿到文件路径
	if err != nil {
		global.GVA_LOG.Error("修改数据库链接失败!", zap.Error(err))
		response.FailWithMessage("修改数据库链接失败", c)
		return
	}
	response.OkWithDetailed(fileInfo, "上传成功", c)
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: UploadFile
//@description: 根据配置文件判断是文件上传到本地或者七牛云
//@param: header *multipart.FileHeader, noSave string
//@return: file files.Flie, err error

func (f *FilesApi) UploadFile(header *multipart.FileHeader, noSave string, typeInfo int8, userId uint) (fileInfo files.Files, err error) {
	oss := upload.NewOss()
	filePath, _, uploadErr := oss.UploadFile(header)
	if uploadErr != nil {
		panic(uploadErr)
	}

	fileInfo = files.Files{
		FileName: header.Filename,
		FilePath: filePath,
		Type:     typeInfo,
		UserId:   userId,
	}
	if noSave == "0" {
		fileInfo, err = service.ServiceGroupApp.FilesServiceGroup.CreateFile(fileInfo)
		if err != nil {
			return files.Files{}, err
		}
		return fileInfo, nil
	}
	return fileInfo, nil
}
